<template>
  <!-- 简单导航 -->
  <SimpleNav/>
  <section class="login-form">
    <!-- 定义一个容器、水平垂直居中 -->
    <main class="login-container">
      <div class="login-bg"></div>
      <div class="login-core">
        <div class="login-tab" @click="swtichTab">
          <span data-name="0" :class="{active: switchType}">用户登录</span>
          <span data-name="1" :class="{active: !switchType}">用户注册</span>
        </div>
        <!-- 显示登录组件 -->
        <div class="login-panel">
            <el-form :model="login" v-show="switchType" style="width: 100%">
              <el-form-item>
                <el-input v-model="login.username" size="large" placeholder="请输入邮箱账号/用户名">
                  <template #suffix>
                    <el-icon :size="26">
                      <Message/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-input v-model="login.password" type="password" size="large" placeholder="请输入密码">
                  <template #suffix>
                    <el-icon :size="26">
                      <Unlock/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="login.rememberMe" size="large">30天自动登录</el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="large" style="width: 100%;"
                  :loading="loginLoading"
                  :disabled="loginLoading"
                  @click.prevent="onSubmitLogin"
                >登录</el-button>
              </el-form-item>
              <a class="login-fda" @click="findPass">忘记密码，点我找回</a>
            </el-form>

            <el-form :model="form" v-show="!switchType"  style="width: 100%">

              <el-form-item>
                <el-input v-model="form.username" size="large" placeholder="请输入用户名">
                  <template #suffix>
                    <el-icon :size="26">
                      <UserFilled />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-input v-model="form.email" size="large" placeholder="请输入邮箱账号">
                  <template #suffix>
                    <el-icon :size="26">
                      <Message/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-input v-model="form.password" type="password" size="large" placeholder="请输入密码">
                  <template #suffix>
                    <el-icon :size="26">
                      <Unlock/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-input v-model="form.password2" type="password" size="large" placeholder="请再次输入密码">
                  <template #suffix>
                    <el-icon :size="26">
                      <Unlock/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item >
                <el-select v-model="form.clazz_id" size="large" clearable placeholder="请选择班级">
                    <el-option v-for="clz in clazzList" :key="clz.id" :label="clz.name" :value="clz.id" />
                </el-select>
              </el-form-item>


              <el-form-item>
                <el-input v-model="form.name" size="large" placeholder="请输入真实姓名">
                  <template #suffix>
                    <el-icon :size="26">
                      <User/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

            
              <el-form-item>
                <el-button type="primary" size="large" style="width: 100%;" @click.prevent="onSubmitRegister">注册</el-button>
              </el-form-item>
            </el-form>
        </div>

      </div>
    </main>
  </section>
</template>
<script>
import router from '@/router';
import SimpleNav from '@/components/SimpleNav.vue'
import API from '@/api/index.js';
import Token from '@/api/token.js';
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      switchType: true, // 控制登录或注册
      login: {
        username: '',
        password: '',
        rememberMe: true,
      },
      form: {
        username: "",
        email: "",
        password: "",
        password2: "",
        name: "",
        clazz_id: null,
      },
      clazzList: [],
      loginLoading: false, // 新增loading状态
    };
  },

  created() {
    API.getClazzList()
    .then(res => {
      this.clazzList = res.classes; 
      console.log("clazzList after assignment:", this.clazzList);
    }).catch(error => {
      console.error("Error fetching class list:", error);
    });
  },

  methods: {
    swtichTab(event) {
      if (event.target.nodeName === "SPAN") {
        this.switchType = event.target.dataset.name !== "1";
      }
    },
    
    async onSubmitLogin() {
      if (this.loginLoading) return;
      this.loginLoading = true;
      try {
        if (!this.login.username) {
          this.$layer.msg("请输入邮箱账号或用户名");
          this.loginLoading = false;
          return;
        }
        if (this.login.password === '') {
          this.$layer.msg("密码不能为空");
          this.loginLoading = false;
          return;
        }
        const res = await API.login(this.login);
        this.$layer.msg("登录成功！");
        Token.saveToken(res.access, res.refresh, this.login.rememberMe);
        this.$router.push({ name: 'home' });
      } catch (e) {
        // 登录失败自动有 layer 提示
      } finally {
        this.loginLoading = false;
      }
    },

    async onSubmitRegister() {
      try {
        const registerData = {
          username: this.form.username,
          password: this.form.password,
          email: this.form.email,
          name: this.form.name,
          clazz_id: this.form.clazz_id
        }

        await API.register(registerData)
        
        ElMessage({
          type: 'success',
          message: '注册成功!'
        })

        // 注册成功后自动切换到登录面板
        this.switchType = true
        
        // 清空注册表单
        this.form = {
          email: "",
          password: "",
          password2: "",
          name: "",
          tel: "",
          clazz: "",
          userType: 2
        }
        
      } catch (error) {
        ElMessage({
          type: 'error',
          message: error.response?.data?.message || '注册失败,请重试'
        })
      }
    },

    findPass() {
      this.$router.push({name: 'find-pwd'})
    }
  },
  components: {
    SimpleNav,
  }
};
</script>

<style scoped>
.login-form {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  user-select: none;
  box-sizing: border-box;
  height: calc(100vh - 61px);
}

.login-container {
  width: 900px;
  height: 560px;
  background-color: #f0f0f0;
  display: flex;
  border-radius: 20px 0 0 20px;
}

.login-bg {
  position: relative;
  width: 300px;
  background: #333 url(../assets/task-login-bg.png) no-repeat center / 230%;
  border-radius: 20px 0 0 20px;
  box-shadow: 0 0 10px #000;
}

.login-core {
  flex: auto 1 1;
}

.login-tab {
  height: 120px;
  line-height: 120px;
  text-align: center;
  font-size: 18px;
}

.login-tab span {
  padding: 10px 30px;
  cursor: pointer;
  position: relative;
  margin: 0 5px;
}

.login-tab span::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
}

.login-tab span.active::after {
  height: 4px;
  width: 100%;
  background-color: #5FB878;
  transition: all .5s;
}

.login-panel {
  padding: 10px 40px;
}

.login-fda {
  float: right !important;
  font-size: 14px;
}

@media (max-width: 600px) {
  .login-form {
    height: auto;
    min-height: 100vh;
    padding: 0;
    background: #f0f0f0;
  }
  .login-container {
    width: 100vw;
    min-width: 0;
    max-width: 100vw;
    height: auto;
    min-height: 100vh;
    border-radius: 0;
    flex-direction: column;
    box-shadow: none;
    background: #f0f0f0;
    padding: 0;
  }
  .login-bg {
    display: none;
  }
  .login-core {
    width: 100vw;
    min-width: 0;
    padding: 0;
  }
  .login-tab {
    height: 60px;
    line-height: 60px;
    font-size: 16px;
    padding-top: 10px;
  }
  .login-panel {
    padding: 10px 12px;
  }
  .el-form-item {
    margin-bottom: 16px !important;
  }
  .el-input__wrapper, .el-input__inner, .el-select {
    font-size: 15px !important;
  }
  .el-button {
    font-size: 16px !important;
    height: 40px !important;
  }
  .login-fda {
    float: none !important;
    display: block;
    text-align: right;
    margin-top: -8px;
    margin-bottom: 8px;
  }
}
</style>